<template>
  <div class="home-doctor">
    <div class="top">
      <div class="avatar-wrap" v-if="roleId==4">
        <div style="margin-bottom: 10px;">头像(点击可更换)：</div>
        <el-upload ref="xx" class="avatar-uploader" :action="uploadAction" :data="{
                  uploadType: 1,
                }" :show-file-list="false" :multiple="false" :auto-upload="true" :headers="headers" :on-change="
              (r, f) => {
                handleFileChange(r, f);
              }
            " :on-success="
              (r, f) => {
                uploadSuccess(r, f);
              }
            ">
          <img v-if="userData.avatar" :src="userData.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <br />
        <a @click="showQrcode">医生二维码<i class="el-icon-arrow-right"></i></a>
      </div>
      <div class="user-info" v-if="roleId==4">
        <span>姓名：</span>{{userData.name}}<br />
        <span>职称：</span>{{userData.postName}}<br />
        <span>科室：</span>{{userData.departmentName}}<br />
        <span>医院：</span>{{userData.hospitalName}}<br />
        <a @click="showUserInfo">更多个人信息<i class="el-icon-arrow-right"></i></a><br />
      </div>
      <div class="statistics pointer">
        <div class="statistics-title">统计：</div>

        <div class="statistics-item" @click="goMyPatient(1)">
          <span>{{ stData.hasTestNum || 0 }}</span><br />
          今日已测量
        </div>
        <div class="statistics-item" @click="goMyPatient(2)">
          <span>{{ stData.notTestNum || 0 }}</span><br />
          今日未测量
        </div>
        <div class="statistics-item" @click="goMyPatient(3)">
          <span>{{ stData.abnormalNum || 0 }}</span><br />
          今日异常
        </div>
        <div class="statistics-item" @click="goMyPatient(4)">
          <span>{{ stData.potentialLossNum||  0 }}</span><br />
          潜在流失
        </div>
        <div class="statistics-item">
          <span>{{ stData.beCaredNum||  0 }}</span><br />
          累计已关怀人次
        </div>
        <div class="statistics-item" @click="goMyPatient(0)">
          <span>{{ stData.patientNum || 0 }}</span><br />
          患者数
        </div>
        <div class="statistics-item" @click="goMyPatient(8)">
          <span>{{ stData.prevMonthAddNum || 0 }}</span><br />
          上月新增患者数
        </div>
        <div class="statistics-item" @click="goMyPatient(10)">
          <span>{{ stData.activeNum || 0 }}</span><br />
          活跃患者数
        </div>


        <div class="statistics-item" @click="goMyPatient(6)">
          <span>{{ stData.bindNum || 0 }}</span><br />
          已绑定设备患者数
        </div>
        <div class="statistics-item" @click="goMyPatient(9)">
          <span>{{ stData.prevMonthAddBindNum || 0 }}</span><br />
          上月新增绑定设备的患者数
        </div>
        <div class="statistics-item" @click="goMyPatient(7)">
          <span>{{ stData.unbindNum || 0 }}</span><br />
          未绑定设备患者数
        </div>
        <div class="statistics-item">
          <span>{{ stData.remindNum || 0 }}</span><br />
          今日医生提醒次数
        </div>
      </div>
      <div class="statistics" v-if="roleId==4">
        <div class="statistics-title">患者对我评价：</div>
        <div class="statistics-item">
          <span style="color: rgb(3, 167, 240);">{{ evaluateData.maxScore || 0 }}</span><br />
          最高分
        </div>
        <div class="statistics-item">
          <span style="color: #e83112;">{{ evaluateData.minScore || 0 }}</span><br />
          最低分
        </div>
        <div class="statistics-item">
          <span style="color:  #e6a23c">{{ evaluateData.totalAvgScore||  0 }}</span><br />
          平均分
        </div>
        <div class="statistics-item">
          <span>{{ evaluateData.goodNum || 0 }}</span><br />
          好评数
        </div>
        <div class="statistics-item">
          <span>{{ evaluateData.badNum || 0 }}</span><br />
          差评数
        </div>
        <div class="statistics-item">
          <span>{{ evaluateData.totalNum || 0 }}</span><br />
          评分总次数
        </div>
        <!-- <div class="statistics-item">
         <span>{{ evaluateData.patientNum || 0 }}</span
         ><br />
         患者人数
       </div> -->
        <div class="statistics-item">
          <span>{{ evaluateData.interactNum || 0 }}</span><br />
          互动量
        </div>
      </div>
    </div>
    <div class="table-more">
      <span @click="goMyPatient(1)">更多<i class="el-icon-arrow-right"></i></span>
    </div>
    <el-table v-loading="tableLoading" ref="table" :data="tableData" border stripe style="width: 100%"
      :class="[tableCalss]">
      <el-table-column label="姓名">
        <template slot-scope="scope">
          <span style="cursor: pointer;color:#409EFF" @click="goMyPatient(0,scope.row.name,)">{{
              scope.row.name
            }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="telphone" label="手机号"> </el-table-column>
      <el-table-column prop="age" label="年龄"> </el-table-column>
      <el-table-column label="性别">
        <template slot-scope="scope">
          <span>{{
            scope.row.sex == 1 ? "男" : scope.row.sex == 0 ? "女" : "未知"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="diseaseCategory" label="患者病类"></el-table-column>
      <el-table-column prop="testDate" label="测量时间">
        <template slot-scope="scope">
          {{ scope.row.testDate }}
        </template>
      </el-table-column>

      <el-table-column label="收缩压(mmHg)">
        <template slot-scope="scope">
          <span :style="{
             color:scope.row.isSbpAbnormal ? colors[scope.row.sbpAbnormalLevel-1] : '',
           }">{{ scope.row.sbp }}</span>
        </template>
      </el-table-column>
      <el-table-column label="舒张压(mmHg)">
        <template slot-scope="scope">
          <span :style="{
              color: scope.row.isDbpAbnormal ? colors[scope.row.dbpAbnormalLevel-1] : '',
            }">{{ scope.row.dbp }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="postName" label="脉搏(次/分)">
        <template slot-scope="scope">
          {{ scope.row.hr }}
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="个人信息" :visible.sync="openView" width="1200px" append-to-body>
      <basics-form ref="basicsAddForm" :minWidth="'400px'" :titleAligin="'right'" :titleWidth="'130px'"
        :actionLoading="loading" @actionBtnsClick="addAction" @submit="addSubmit" />
    </el-dialog>
    <el-dialog title="医生二维码" :visible.sync="openQrcode" width="600px" append-to-body>
      <div>
        <div style="text-align: center;">鼠标移至二维码，点击鼠标右键，选择“图片另存为”可保存二维码</div>
        <div id="qrCode" ref="qrCodeDiv" style="margin: 20px 0 0 180px;"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import BasicsForm from "@/components/BasicsForm";
  import {
    getToken
  } from "@/utils/auth";
  import {
    parseTime
  } from "@/utils/ruoyi";
  import {
    doctorDetailOfWeb,
    getHomeInfoOfWeb,
    dictDataForDoctor,
    updateDoctorOfWeb,
    countEvaluateOfWeb,
    newestBloodTestList
  } from "@/api/manbing/doctor";
  import QRCode from 'qrcodejs2';
  export default {
    name: "home-doctor",
    components: {
      BasicsForm
    },
    data() {
      return {
        colors: ['#409EFF', 'rgb(253,154,1)', 'red'], //警告颜色
        roleId: sessionStorage.getItem("roleId"),
        uploadAction: process.env.VUE_APP_BASE_API + "/chronicdisease/plat/uploadFile",
        headers: {
          Authorization: "Bearer " + getToken(),
          roleId: sessionStorage.getItem("roleId"),
        },
        userData: {}, //用户信息
        stData: {}, //统计信息
        evaluateData: {}, //评分信息
        openView: false,
        openQrcode: false,
        qrCodeFlag: true,
        loading: false,
        dictData: null, //科室职务

        tableLoading: false,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          searchType: 1,
        },
        tableData: [],
        tableCalss: '',
        websock: null,
      };
    },
    created() {
      if (this.roleId == 4) {
        this.getDoctorDetailOfWeb()
      }
      this.homeInfoOfWeb()
      this.getCountEvaluateOfWeb()
      this.getNewestBloodTestList()
      this.initWebSocket()
    },
    methods: {
      //测量数据
      getNewestBloodTestList() {
        this.loading = true;
        this.tableLoading = true;
        newestBloodTestList(this.queryParams)
          .then((res) => {
            if (res.code == 200) {
              this.tableData = res.data;
            }
          })
          .finally(() => {
            this.loading = false;
            this.tableLoading = false;
          });
      },
      initWebSocket() { //初始化weosocket
        const wsuri = process.env.VUE_APP_BASE_API.replace('http', 'ws') + "/websocket";
        this.websock = new WebSocket(wsuri);
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        // this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
        this.$bus.$on('websocketonmessage', this.handleMessage)
      },
      websocketclose() {
        this.initWebSocket()
      },
      websocketonopen() { //连接建立之后执行send方法发送数据
        let userId = JSON.parse(sessionStorage.getItem('user')).userId,
          roleId = sessionStorage.getItem('roleId');
        this.websocketsend(`${userId}#${roleId}#${getToken()}`);
      },
      websocketsend(Data) { //数据发送
        this.websock.send(Data);
      },
      websocketonmessage(e) { //数据接收
        this.$bus.$emit('websocketonmessage', e)
      },
      handleMessage(e) {
        try {
          if (e.data && e.data != '连接成功') {
            if (e.data == '更新统计') {
              this.homeInfoOfWeb()
              return
            }
            let temp = JSON.parse(e.data)
            temp.testDate = parseTime(new Date(temp.testDate))
            this.tableData.unshift(temp)
            this.tableCalss = 'my-table'
            setTimeout(() => {
              this.tableCalss = 'my-table2'
              setTimeout(() => {
                this.tableCalss = ''
              }, 2000)
            }, 1000)
            if (this.tableData.length > 10) {
              this.tableData.splice(10, 1)
            }
            this.$notify({
              title: '通知',
              message: '有新的测量数据',
              type: 'success'
            });

          }
        } catch (e) {

        }
      },
      //医生信息
      getDoctorDetailOfWeb() {
        doctorDetailOfWeb({}).then(res => {
          if (res.code == 200) {
            this.userData = res.data
          }
        })
      },
      //统计
      homeInfoOfWeb() {
        getHomeInfoOfWeb({}).then(res => {
          if (res.code == 200) {
            this.stData = res.data
          }
        })
      },
      //评分
      getCountEvaluateOfWeb() {
        countEvaluateOfWeb({}).then(res => {
          if (res.code == 200) {
            this.evaluateData = res.data||{}
          }
        })
      },
      //显示个人信息
      showUserInfo() {
        this.openView = true
        this.$nextTick(() => {
          this.getDictDataForDoctor(true);
        });
      },
      //显示医生二维码
      showQrcode() {
        this.openQrcode = true
        if (this.qrCodeFlag) {
          this.qrCodeFlag = false
          this.$nextTick(() => {
            new QRCode(this.$refs.qrCodeDiv, {               text: 'https://hqkh.scihi.cn?doctorId=' + this.userData.doctorId,               width: 200,               height: 200,                colorDark: "#333333", //二维码颜色               colorLight: "#ffffff", //二维码背景色
              correctLevel: QRCode.CorrectLevel.L //容错率，L/M/H             })
          })
        }
      },
      //职务和科室下拉字典数据
      getDictDataForDoctor() {
        if (this.dictData) {
          this.initAddRules();
        } else {
          dictDataForDoctor({}).then((res) => {
            if (res.code == 200) {
              this.dictData = res.data;
              this.initAddRules();
            }
          });
        }
      },
      initAddRules() {
        let item = this.userData.doctorId ? this.userData : {},
          departmentIdValue = "",
          postIdValue = "";

        if (item.departmentId) {
          this.dictData.departmentList.some((it, index) => {
            if (it.deptId == item.departmentId) {
              departmentIdValue = index;
              return true;
            }
          });
        }
        if (item.postId) {
          this.dictData.postList.some((it, index) => {
            if (it.postId == item.postId) {
              postIdValue = index;
              return true;
            }
          });
        }
        let rules = [{
            title: "医院",
            key: "hospitalName",
            disabled: true,
            value: this.userData.hospitalName,
            skip: true,
            disabled: true
          },
          {
            title: "姓名",
            key: "name",
            value: item.name || "",
          },
          {
            title: "手机号(账号)",
            key: "phone",
            maxlength: 11,
            ruleList: ["isMobile"],
            ruleMsgList: ["请输入正确的手机号码"],
            value: item.phone || "",
            disabled: true,
            skip: true,
          },
          {
            title: "工号",
            key: "jobNo",
            skip: true,
            value: item.jobNo || "",
            disabled: true,
          },
          {
            title: "身份证号",
            key: "idCard",
            ruleList: ["isIdCard"],
            ruleMsgList: ["请输入正确的身份证号"],
            skip: true,
            value: item.idCard || "",
          },

          {
            title: "性别",
            key: "sex",
            type: "radio",
            selectList: [{
                name: "男",
                value: "1"
              },
              {
                name: "女",
                value: "0"
              },
            ],
            selectKey: "value",
            skip: true,
            value: item.sex != undefined && item.sex > -1 ? 1 - item.sex : "",
          },
          {
            title: "科室",
            key: "departmentId",
            type: "select",
            selectList: this.dictData.departmentList,
            selectKey: "deptId",
            selectShowKey: "deptName",
            skip: true,
            value: departmentIdValue,
          },
          {
            title: "职务",
            key: "postId",
            type: "select",
            selectList: this.dictData.postList,
            selectKey: "postId",
            selectShowKey: "postName",
            skip: true,
            value: postIdValue,
          },
          {
            title: "职业起始年限",
            key: "occupationStartYear",
            type: "year",
            skip: true,
            value: item.occupationStartYear || "",
          },
          {
            title: "擅长病种",
            key: "goodAtDisease",
            type: "textarea",
            skip: true,
            value: item.goodAtDisease || "",
          },
          {
            title: "专业特长",
            key: "specialty",
            type: "textarea",
            skip: true,
            value: item.specialty || "",
          },
          {
            title: "简介",
            key: "introduction",
            type: "textarea",
            skip: true,
            value: item.introduction || "",
          },
          {
            title: "身份证照片",
            key: "idCardUrl",
            type: "img",
            skip: true,
            uploadExtra: {
              uploadType: 1,
            },
            uploadAction: process.env.VUE_APP_BASE_API + "/chronicdisease/plat/uploadFile",
            value: item.idCardUrl || "",
          },
          {
            title: "执业资格证照片",
            key: "certificateUrl",
            type: "img",
            skip: true,
            uploadExtra: {
              uploadType: 1,
            },
            uploadAction: process.env.VUE_APP_BASE_API + "/chronicdisease/plat/uploadFile",
            value: item.certificateUrl || "",
          }, {
            type: "actionBtns",
            selectList: [{
                name: "取消",
                value: ""
              },
            {
                name: "提交",
                value: "primary"
              },
            ],
            btnsAligin: "center",
            ruleWidth: "100%",
          }
        ];
        this.$refs.basicsAddForm.initForm(rules);
      },
      addAction(index) {
        if (index) {
          this.$refs.basicsAddForm.formValid();
        } else {
          this.openView = false;
        }
      },
      addSubmit(param) {
        if (!param) {
          return;
        }
        this.loading = true;
        param.doctorId = this.userData.doctorId;
        param.hospitalId = this.userData.hospitalId;
        for (let key in param) {
          if (!param[key]) {
            param[key] = ''
          }
        }
        updateDoctorOfWeb(param)
          .then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess("修改成功");
              this.openView = false;
              this.getDoctorDetailOfWeb();
            }
          })
          .finally(() => {
            this.loading = false;
          });
      },
      //文件预览
      handleFileChange(res, fileList) {
        if (fileList.length) {
          this.userData.avatar = URL.createObjectURL(res.raw);
        }
      },
      //文件预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url || file;
        this.dialogVisible = true;
      },
      uploadSuccess(res, file) {
        if (res.code == 200) {
          let userData = this.userData
          userData.avatar = res.data
          updateDoctorOfWeb(userData)
            .then((res1) => {
              if (res1.code == 200) {
                this.$modal.msgSuccess("头像上传成功");
                this.userData.avatar = res.data;
              } else {
                this.$modal.msgError("头像上传失败");
              }
            })
        } else {
          this.$modal.msgError("头像上传失败");
        }
      },
      //前往我的患者
      goMyPatient(value, patientName) {
        if (patientName) {
          this.$router.push('/manbing/patient?patientName=' + patientName)
        } else {
          this.$router.push('/manbing/patient?type=' + value)
        }
      }
    },
  };
</script>
<style scoped lang="scss">
  @keyframes example {
    from {
      transform: translateY(-50px);
    }

    to {
      transform: translateY(0px);
    }
  }

  @keyframes example2 {
    0% {
      background: #409EFF;
    }

    99% {
      background: #409EFF;
    }

    0% {
      background: #fff;
    }
  }

  ::v-deep .my-table {
    .el-table__row {
      width: 100%;
      animation: example 1s infinite;
    }
  }

  ::v-deep .my-table2 {
    .el-table__row:first-child {
      width: 100%;
      animation: example2 2s infinite;
    }
  }

  .home {
    .top {
      display: flex;

      .avatar-wrap {
        .avatar-uploader .el-upload {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
        }

        .avatar-uploader-icon {
          border: 1px dashed #d9d9d9;
        }

        .avatar-uploader .el-upload:hover {
          border-color: #409eff;
        }

        .avatar-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          width: 178px;
          height: 178px;
          line-height: 178px;
          text-align: center;
        }

        .avatar {
          width: 178px;
          height: 178px;
          display: block;
        }

        a {
          color: rgb(3, 167, 240);
          margin: 40px 0 0 40px;
        }
      }

      .user-info {
        margin: 20px 0 0 40px;
        line-height: 40px;
        min-width: 140px;

        span {
          color: #8c939d;
        }

        a {
          color: rgb(3, 167, 240)
        }
      }

      .statistics {
        margin: 0px 0 0 80px;
        display: flex;
        flex-wrap: wrap;
        position: relative;
        border: 1px solid rgba(0, 0, 0, 0.2);
        border-radius: 10px;

        &-title {
          padding: 4px 0 0 10px;
          width: 100%;
        }

        &-item {
          margin-bottom: 10px;
          width: 33.33%;
          text-align: center;
          color: #8c939d;

          span {
            color: #434343;
            font-size: 24px;
          }
        }

      }

      .pointer {
        .statistics-item {
          cursor: pointer;
        }
      }
    }

    .table-more {
      margin: 30px 0 10px 0;
      text-align: right;

      span {
        cursor: pointer;
        color: rgb(3, 167, 240)
      }
    }

  }
</style>
